﻿using AchieveBLL;
using AchieveCommon;
using AchieveEntity;
using AchieveManageWeb.Models;
using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using System.Text;
using System.Data.SqlClient;

namespace AchieveManageWeb.Controllers
{
     [AchieveManageWeb.App_Start.JudgmentLogin]
    public class GISController : Controller
    {
        //
        // GET: /GIS/

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult UserLocationEdit()
        {
            AchieveManageWeb.Models.ActionFilters.LoggerHelper.Notes(new LogContent(ViewData, "访问视图", "UserLocationEdit")); //日志记录
            return View();
        }
        public ActionResult UserLocation()
        {
            AchieveManageWeb.Models.ActionFilters.LoggerHelper.Notes(new LogContent(ViewData, "访问视图", "UserLocation")); //日志记录
            return View();
        }
        public ActionResult UserLocationGIS()
        {
            AchieveManageWeb.Models.ActionFilters.LoggerHelper.Notes(new LogContent(ViewData, "访问视图", "UserLocationGIS")); //日志记录
            return View();
        }
         
          
             public ActionResult getRegion()
        {
    int     pRegionCode = Convert.ToInt32("0"+Request["pRegionCode"]);
    string sql = "select * from tbRegionCode where pRegionCode=" + pRegionCode;
    DataTable dt = SqlHelper.GetDataTable(SqlHelper.connStr, sql);

    return Content(JsonHelper.ToJson(dt));
        }
        public ActionResult GetAllUserInfo()
        {
            string strWhere = "1=1";
            string sort = Request["sort"] == null ? "ID" : Request["sort"];
            string order = Request["order"] == null ? "asc" : Request["order"];
            string RoleIDs = Request["RoleIDs[]"] ?? "";  //角色id，可能是多个,"55,11,32",待处理
            string DeptIds = Request["DeptIds[]"] ?? "";  //部门id，可能是多个

            //首先获取前台传递过来的参数
            int pageindex = Request["page"] == null ? 1 : Convert.ToInt32(Request["page"]);
            int pagesize = Request["rows"] == null ? 10 : Convert.ToInt32(Request["rows"]);
            string userid = Request["accountid"] == null ? "" : Request["accountid"];
            string username = Request["username"] == null ? "" : Request["username"];
            string isable = Request["isable"] == null ? "" : Request["isable"];
            string ifchangepwd = Request["ifchangepwd"] == null ? "" : Request["ifchangepwd"];
            string userperson = Request["userperson"] == null ? "" : Request["userperson"];
            string adddatestart = Request["adddatestart"] == null ? "" : Request["adddatestart"];
            string adddateend = Request["adddateend"] == null ? "" : Request["adddateend"];

            if (userid.Trim() != "" && !SqlInjection.GetString(userid))   //防止sql注入
                strWhere += string.Format(" and AccountName like '%{0}%'", userid.Trim());
            if (username.Trim() != "" && !SqlInjection.GetString(username))
                strWhere += string.Format(" and RealName like '%{0}%'", username.Trim());
            if (isable.Trim() != "select" && isable.Trim() != "")
                strWhere += " and IsAble = '" + isable.Trim() + "'";
            if (ifchangepwd.Trim() != "select" && ifchangepwd.Trim() != "")
                strWhere += " and IfChangePwd = '" + ifchangepwd.Trim() + "'";
            if (adddatestart.Trim() != "")
                strWhere += " and CreateTime > '" + adddatestart.Trim() + "'";
            if (adddateend.Trim() != "")
                strWhere += " and CreateTime < '" + adddateend.Trim() + "'";

            string sql = "select a.accountName,a.realName,regionCode,b.describe,lng,lat,b.updateTime,province,city,county,isNull(isCurrent,0) as isCurrent,b.id from tbuser a left join tbuserlocation b on a.accountname=b.accountname ";
            //sql+=" where a.accountname="

            int totalCount;   //输出参数
            DataTable dt = SqlHelper.GetDataTable(SqlHelper.connStr, sql);
            totalCount = dt.Rows.Count;
            string strJson = JsonHelper.ToJson(dt);
             
            //string strJson = new UserBLL().GetPager("tbUser", "ID,AccountName,[Password],RealName,MobilePhone,Email,IsAble,IfChangePwd,[Description],CreateTime,CreateBy,UpdateTime,UpdateBy", sort + " " + order, pagesize, pageindex, strWhere, out totalCount);
            var jsonResult = new { total = totalCount.ToString(), rows = strJson };
            return Content("{\"total\": " + totalCount.ToString() + ",\"rows\":" + strJson + "}");
        }
        /// <summary>
        /// 编辑 用户
        /// </summary>
        /// <returns></returns>
        public ActionResult EditUserLocation()
        {
            try
            {
                 int regionCode = Convert.ToInt32("0"+Request["regionCode"]);
                 int id = string.IsNullOrEmpty(Request["id"]) ? 0 : Convert.ToInt32(Request["id"]);
                  
                 string accountname = Request["accountName"];
                 string realname = Request["realName"];
                string describe = Request["locDescribe"];
                string province = Request["province"];
                string county = Request["county"];
                string city = Request["city"];
                decimal lng = Convert.ToDecimal("0"+Request["lng"]);
                decimal lat = Convert.ToDecimal("0"+Request["lat"]);
                bool isCurrent = Convert.ToBoolean(Request["isCurrent"]);
                 DateTime UpdateTime = DateTime.Now;
                 if (id>0)//已有记录,更新
                 {
                    StringBuilder strSql = new StringBuilder();
                     strSql.Append("update [tbUserLocation] set ");
                     strSql.Append("accountname=@accountname,");
                     strSql.Append("realname=@realname,");
                     strSql.Append("regionCode=@regionCode,");
                     strSql.Append("describe=@describe,");
                     strSql.Append("lng=@lng,");
                     strSql.Append("lat=@lat,");
                     strSql.Append("UpdateTime=@UpdateTime,");
                     strSql.Append("province=@province,");
                     strSql.Append("city=@city,");
                     strSql.Append("county=@county,");
                     strSql.Append("isCurrent=@isCurrent");
                     strSql.Append(" where id=@id ");
                     SqlParameter[] parameters = {
					new SqlParameter("@accountname", SqlDbType.NVarChar,50),
					new SqlParameter("@realname", SqlDbType.NVarChar,50),
					new SqlParameter("@regionCode", SqlDbType.Int,4),
					new SqlParameter("@describe", SqlDbType.NVarChar,50),
					new SqlParameter("@lng", SqlDbType.Decimal,9),
					new SqlParameter("@lat", SqlDbType.Decimal,9),
					new SqlParameter("@UpdateTime", SqlDbType.DateTime),
					new SqlParameter("@province", SqlDbType.NVarChar,50),
					new SqlParameter("@city", SqlDbType.NVarChar,50),
					new SqlParameter("@county", SqlDbType.NVarChar,50),
					new SqlParameter("@isCurrent", SqlDbType.Bit,1),
					new SqlParameter("@id", SqlDbType.Int,4)};
                     parameters[0].Value = accountname;
                     parameters[1].Value = realname;
                     parameters[2].Value = regionCode;
                     parameters[3].Value = describe;
                     parameters[4].Value = lng;
                     parameters[5].Value = lat;
                     parameters[6].Value = UpdateTime;
                     parameters[7].Value = province;
                     parameters[8].Value = city;
                     parameters[9].Value = county;
                     parameters[10].Value = isCurrent;
                     parameters[11].Value = id;

                     int rows = SqlHelper.ExecuteNonQuery(SqlHelper.connStr, CommandType.Text, strSql.ToString(), parameters);
                     //DbHelperSQL.ExecuteSql(strSql.ToString(),parameters);
                     if (rows > 0)
                     {
                         return Content("{\"msg\":\"修改成功！\",\"success\":true}");
                     }
                     else
                     {
                         return Content("{\"msg\":\"修改失败！\",\"success\":true}");
                     }

                 }
                 else //无记录，插入
                 {
                     StringBuilder strSql = new StringBuilder();
                     strSql.Append("insert into [tbUserLocation] (");
                     strSql.Append("accountname,realname,regionCode,describe,lng,lat,UpdateTime,province,city,county,isCurrent)");
                     strSql.Append(" values (");
                     strSql.Append("@accountname,@realname,@regionCode,@describe,@lng,@lat,@UpdateTime,@province,@city,@county,@isCurrent)");
                     strSql.Append(";select @@IDENTITY");
                     SqlParameter[] parameters = {
					new SqlParameter("@accountname", SqlDbType.NVarChar,50),
					new SqlParameter("@realname", SqlDbType.NVarChar,50),
					new SqlParameter("@regionCode", SqlDbType.Int,4),
					new SqlParameter("@describe", SqlDbType.NVarChar,50),
					new SqlParameter("@lng", SqlDbType.Decimal,9),
					new SqlParameter("@lat", SqlDbType.Decimal,9),
					new SqlParameter("@UpdateTime", SqlDbType.DateTime),
					new SqlParameter("@province", SqlDbType.NVarChar,50),
					new SqlParameter("@city", SqlDbType.NVarChar,50),
					new SqlParameter("@county", SqlDbType.NVarChar,50),
					new SqlParameter("@isCurrent", SqlDbType.Bit,1)};
                     parameters[0].Value = accountname;
                     parameters[1].Value = realname;
                     parameters[2].Value = regionCode;
                     parameters[3].Value = describe;
                     parameters[4].Value = lng;
                     parameters[5].Value = lat;
                     parameters[6].Value = UpdateTime;
                     parameters[7].Value = province;
                     parameters[8].Value = city;
                     parameters[9].Value = county;
                     parameters[10].Value = isCurrent;

                     object obj = SqlHelper.ExecuteScalar(SqlHelper.connStr, CommandType.Text, strSql.ToString(), parameters);
                     // DbHelperSQL.GetSingle(strSql.ToString(),parameters);
                     if (obj == null)
                     {
                         return Content("{\"msg\":\"修改失败！\",\"success\":true}");
                     }
                     else
                     {
                         return Content("{\"msg\":\"修改成功！\",\"success\":true}");
                       //  return Convert.ToInt32(obj);
                     }

                    
                 } 

            }
            catch (Exception ex)
            {
                return Content("{\"msg\":\"修改失败," + ex.Message + "\",\"success\":false}");
            }
        }

    }
}
